/** @format */

// copy-files-plugin.js
import fs from 'fs-extra'; // 用于文件操作的增强版 fs
import path from 'path';
import chokidar from 'chokidar'; // 监听文件变化的库
// 源文件夹和目标文件夹
const cloundDir = 'wxcloudfunctions';
const sourceDir = path.join(__dirname, 'src/', cloundDir);
const targetDir = path.join(__dirname, 'dist', process.env.NODE_ENV === 'production' ? 'build' : 'dev', process.env.UNI_PLATFORM, cloundDir);

export default function copyChangedFiles() {
 return {
  name: 'vite-plugin-copy-changed-files',
  generateBundle() {
   // 监听文件夹的变化
   console.log('我要打印的值:', sourceDir);
   console.log('我要打印的值:', targetDir);
   const watcher = chokidar.watch(sourceDir, {
    persistent: true,
    ignoreInitial: true,
   });

   // 处理文件变化
   watcher
    .on('add', (filePath) => copyFile(filePath))
    .on('change', (filePath) => copyFile(filePath))
    .on('unlink', (filePath) => removeFile(filePath));

   // 文件复制函数
   function copyFile(filePath) {
    const targetPath = filePath.replace(sourceDir, targetDir);
    fs
     .copy(filePath, targetPath)
     .then(() => console.log(`File copied: ${targetPath}`))
     .catch((err) => console.error(`Failed to copy file: ${err}`));
   }

   // 文件删除函数
   function removeFile(filePath) {
    const targetPath = filePath.replace(sourceDir, targetDir);
    fs
     .remove(targetPath)
     .then(() => console.log(`File removed: ${targetPath}`))
     .catch((err) => console.error(`Failed to remove file: ${err}`));
   }
  },
 };
}
